package com.zja.servlet;

import com.zja.model.JsonResponse;
import com.zja.model.User;
import com.zja.service.Impl.UserServiceImpl;
import com.zja.service.UserService;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 *@author JA
 *@date: 2025/5/2
 *description:登录
 */
@WebServlet("/api/auth/login")
public class LoginServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码，防止乱码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");


        //获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 调用登录服务
        User user = userService.login(username, password);

        // 登录成功，设置 session
        if (user != null) {
            req.getSession().setAttribute("currentUser", user);
            ServletUtil.writeJsonResponse(resp, JsonResponse.success("登录成功", user.getRole()));
        } else {
            // 登录失败
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("用户名或密码错误"));
        }
    }
}
